const Student = require('../models/student');
const User = require('../models/user');
const passwordUtils = require('../utils/passwordUtils');

// 学生控制器
const studentController = {
  // 获取所有学生
  async getAllStudents(ctx) {
    try {
      const students = await Student.find().populate('classId dormitoryId userId');
      ctx.body = {
        success: true,
        data: students,
        count: students.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取学生列表失败',
        error: error.message
      };
    }
  },

  // 根据ID获取学生
  async getStudentById(ctx) {
    try {
      const student = await Student.findById(ctx.params.id).populate('classId dormitoryId userId');
      if (!student) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '学生不存在'
        };
        return;
      }
      ctx.body = {
        success: true,
        data: student
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取学生信息失败',
        error: error.message
      };
    }
  },

  // 创建学生
  async createStudent(ctx) {
    try {
      const { studentId, name, gender, age, academy, phone, email, status, classId, dormitoryId } = ctx.request.body;

      // 检查学号是否已存在
      const existingStudent = await Student.findOne({ studentId });
      if (existingStudent) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '学号已存在'
        };
        return;
      }

      // 创建用户账号
      const defaultPassword = 'Student123!';
      const hashedPassword = await passwordUtils.hashPassword(defaultPassword);
      const user = new User({
        username: studentId.toLowerCase(),
        name: name,
        email: email || `${studentId}@example.com`,
        password: hashedPassword,
        phone: phone,
        role: 'student',
        status: status || 'active'
      });
      await user.save();

      // 创建学生记录
      const student = new Student({
        studentId,
        name,
        gender,
        age,
        academy,
        phone,
        email: email || `${studentId}@example.com`,
        status: status || 'active',
        classId,
        dormitoryId,
        userId: user._id
      });
      await student.save();

      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '学生创建成功',
        data: student,
        defaultPassword: defaultPassword
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '创建学生失败',
        error: error.message
      };
    }
  },

  // 更新学生信息
  async updateStudent(ctx) {
    try {
      const student = await Student.findById(ctx.params.id);
      if (!student) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '学生不存在'
        };
        return;
      }

      const updateData = ctx.request.body;
      // 更新学生信息
      Object.assign(student, updateData);
      await student.save();

      // 如果需要，更新关联的用户信息
      if (updateData.name || updateData.phone || updateData.email || updateData.status) {
        await User.findByIdAndUpdate(student.userId, {
          name: updateData.name || student.name,
          phone: updateData.phone || student.phone,
          email: updateData.email || student.email,
          status: updateData.status || student.status
        });
      }

      ctx.body = {
        success: true,
        message: '学生信息更新成功',
        data: student
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新学生信息失败',
        error: error.message
      };
    }
  },

  // 删除学生
  async deleteStudent(ctx) {
    try {
      const student = await Student.findById(ctx.params.id);
      if (!student) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '学生不存在'
        };
        return;
      }

      // 删除关联的用户账号
      await User.findByIdAndDelete(student.userId);
      
      // 删除学生记录
      await Student.findByIdAndDelete(ctx.params.id);

      ctx.body = {
        success: true,
        message: '学生删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '删除学生失败',
        error: error.message
      };
    }
  },

  // 分页获取学生列表
  async getStudentsPaginated(ctx) {
    try {
      const page = parseInt(ctx.query.page) || 1;
      const limit = parseInt(ctx.query.limit) || 10;
      const skip = (page - 1) * limit;

      // 构建查询条件
      const query = {};
      if (ctx.query.academy) {
        query.academy = ctx.query.academy;
      }
      if (ctx.query.status) {
        query.status = ctx.query.status;
      }
      if (ctx.query.gender) {
        query.gender = ctx.query.gender;
      }

      const students = await Student.find(query)
        .skip(skip)
        .limit(limit)
        .populate('classId dormitoryId userId')
        .sort({ createdAt: -1 });

      const total = await Student.countDocuments(query);

      ctx.body = {
        success: true,
        data: students,
        pagination: {
          total,
          page,
          limit,
          pages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取分页学生列表失败',
        error: error.message
      };
    }
  },

  // 根据班级获取学生列表
  async getStudentsByClass(ctx) {
    try {
      const students = await Student.find({ classId: ctx.params.classId })
        .populate('dormitoryId userId');
      
      ctx.body = {
        success: true,
        data: students,
        count: students.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级学生列表失败',
        error: error.message
      };
    }
  },

  // 根据宿舍获取学生列表
  async getStudentsByDormitory(ctx) {
    try {
      const students = await Student.find({ dormitoryId: ctx.params.dormitoryId })
        .populate('classId userId');
      
      ctx.body = {
        success: true,
        data: students,
        count: students.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取宿舍学生列表失败',
        error: error.message
      };
    }
  }
};

module.exports = studentController;